package main

import (
	"context"
	"fmt"
	pb "gserver/demo"
	"log"
	"net"
	"os"

	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

const (
	defaultPort = ":9370"
)

type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	fmt.Println("######### get client request name :" + in.Name)
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHi(ctx context.Context, in *pb.HiRequest) (*pb.HiReply, error) {
	fmt.Printf("######### get client request x1, x2: %d, %d\n", in.X1, in.X2)
	return &pb.HiReply{Y: in.X1 + in.X2}, nil
}

func main() {
	port := defaultPort
	if len(os.Args) > 1 {
		port = os.Args[1]
		fmt.Println("Custom Port Config Detected!")
	}
	fmt.Println("Server starting on port " + port)

	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	// Register reflection service on gRPC server.
	reflection.Register(s)
	fmt.Println("grpc server starting on port ", port)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
